/**
 * 画布右键事件
 */

import { openMenu } from '../ContextMenu/ContextMenu'
import { DagChart } from './dag.chart'
import { useDagStore } from '@/stores/dag/dag.store'
import { openFormDialog } from '../FormDialog/FormDialog'
import { ElLoading } from 'element-plus'

const dagStore = useDagStore()

export function initContextmenuEvent(dagChart: DagChart) {
  const { chart } = dagChart
  const canvasDom = chart.getDom()
  let chartEleFlag = false
  chart.on('contextmenu', function (event: any) {
    openElementMenu(event.event.offsetX, event.event.offsetY, event)
    chartEleFlag = true
  })

  canvasDom.addEventListener('contextmenu', (event: any) => {
    if (!chartEleFlag) {
      openCanvasMenu(event.offsetX, event.offsetY)
    }

    chartEleFlag = false
    event.stopPropagation()
    event.preventDefault()
  })
}

/**
 * 打开元素级右键菜单：删除节点、删除边、创建边（连接到...）
 */
function openElementMenu(x: number, y: number, params: any) {
  let option = [
    // {
    //   label: '修改名称',
    //   handle() {
    //     ElementMenuEvents.editNodeName(params.data.name)
    //   }
    // },
    {
      label: '创建边',
      handle() {
        ElementMenuEvents.addEdge(params.data.name)
      }
    },
    {
      label: '删除节点',
      handle() {
        ElementMenuEvents.removeNode(params.data.name)
      }
    }
  ]
  if (params.data.source) {
    // 边
    option = [
      {
        label: '删除边',
        handle() {
          ElementMenuEvents.removeEdge(params.data.source, params.data.target)
        }
      }
    ]
  }
  openMenu(x, y, option)
}

/**
 * 打开画布级右键菜单：创建节点
 */
function openCanvasMenu(x: number, y: number) {
  openMenu(x, y, [
    {
      label: '创建节点',
      handle() {
        CanvasMenuEvents.addNode(x, y)
      }
    }
  ])
}

class ElementMenuEvents {
  /**
   * 修改节点名称
   */
  static editNodeName(oldTaskName: string) {
    if (dagStore.dagChart) {
      const dialog = openFormDialog({
        title: '修改节点名称',
        form: [
          {
            type: 'input',
            label: '节点名称',
            value: oldTaskName
          }
        ],
        async onSubmit(form) {
          const value = form[0].value as string
          if (dagStore.dagChart) {
            const check = dagStore.dagChart.checkTaskName(value)
            if (check) {
              const loading = ElLoading.service()
              await dagStore.dagChart.editNodeName(oldTaskName, value)
              loading.close()
              dagStore.dagChart.refreshChart()
              dialog.close()
            }
          }
        }
      })
    }
  }

  /**
   * 创建边
   */
  static addEdge(name: string) {
    dagStore?.dagChart?.addEdgeStart(name)
  }

  /**
   * 删除节点
   */
  static removeNode(name: string) {
    dagStore?.dagChart?.removeNode(name)
  }

  /**
   * 删除边
   */
  static removeEdge(source: string, target: string) {
    dagStore?.dagChart?.removeEdge(source, target)
  }
}

class CanvasMenuEvents {
  /**
   * 创建节点
   */
  static addNode(x: number, y: number) {
    if (dagStore.dagChart) {
      const [left, top] = dagStore.dagChart.chart.convertFromPixel({ seriesIndex: 0 }, [x, y])
      const dialog = openFormDialog({
        title: '创建节点',
        form: [
          {
            type: 'input',
            label: '节点名称',
            value: ''
          }
        ],
        onSubmit(form) {
          const value = form[0].value as string
          if (dagStore.dagChart) {
            const check = dagStore.dagChart.checkTaskName(value)
            if (check) {
              dagStore.dagChart.addNode(value, left, top)
              dialog.close()
            }
          }
        }
      })
    }
  }
}
